我們需要在Views.py
裡設定輸入進去的數據才能讓資料表正確存取我們需要的有效資料,也可以讓資料進行邏輯判斷後再寫進資料表中,我們在Views.py
加入以下指令:
<views.py>
from django.http import JsonResponse
import json
def classlist(request):
if request.method == 'POST':
data = json.loads(request.body)
Grade = data['Grade']
Class = data['Class']
Gender = data['Gender']
Number = data['Number']
Name = data['Name']
outputinfo={}
if Grade!='' and Class!='' and Gender!='' and Number!='' and Name!='':
count = Classlist.objects.filter(Name=Name).count()
if count == 0:
classlistDB = Classlist.objects.create(Grade=Grade,
Class=Class,
Gender=Gender,
Number=Number,
Name=Name)
outputinfo = {"資料輸入成功,輸出結果":
{"Grade": classlistDB.Grade,
"Class": classlistDB.Class,
"Gender": classlistDB.Gender,
"Number": classlistDB.Number,
"Name": classlistDB.Name,
"Upload_Time": classlistDB.Upload_Time,
"Last_Modified": classlistDB.Last_Modified}}
else:
outputinfo['資料錯誤']= "姓名已存在"
else:
outputinfo['資料錯誤'] = "輸入資料不為空"
else:
outputinfo['資料錯誤'] = "請使用POST輸入"
return JsonResponse(outputinfo,safe=False,
json_dumps_params={'ensure_ascii':False})
上面看起來有些複雜,這裡來分析一下,將程式碼拆分成八個部分:
from django.http import JsonResponse
import json
if request.method == 'POST':
else:
outputinfo['資料錯誤'] = "請使用POST輸入"
data = json.loads(request.body)
Grade = data['Grade']
Class = data['Class']
Gender = data['Gender']
Number = data['Number']
Name = data['Name']
if Grade != '' and Class != '' and Gender != '' and Number != '' and Name!='':
else:
outputinfo['資料錯誤'] = "輸入資料不為空"
count = Classlist.objects.filter(Name=Name).count()
if count == 0:
else:
outputinfo['資料錯誤']= "姓名已存在"
classlistDB = Classlist.objects.create(Grade=Grade,Class=Class,Gender=Gender,
Number=Number,Name=Name)
outputinfo = {"資料輸入成功,輸出結果":
{"Grade": classlistDB.Grade,
"Class": classlistDB.Class,
"Gender": classlistDB.Gender,
"Number": classlistDB.Number,
"Name": classlistDB.Name,
"Upload_Time": classlistDB.Upload_Time,
"Last_Modified": classlistDB.Last_Modified}}
return JsonResponse(outputinfo,safe=False,
json_dumps_params={'ensure_ascii': False})
Views.py
部分就先設定到這裡,需要花一些時間消化理解一下哦!
下回再處理其他的設定,先到這裡,大家掰掰~
標題梗來源:北有戰鬥陀螺 (?)